package it.antonio.ilpizze.servlet.core;

import it.antonio.ilpizze.servlet.Filter;
import it.antonio.ilpizze.servlet.IlPizzeFilter;
import it.antonio.ilpizze.servlet.IlPizzeServlet;
import it.antonio.ilpizze.servlet.Path;

import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class Router {
	private List<Entry> actions = new LinkedList<Entry>();
	
	public void load(Class<? extends IlPizzeServlet> clazz){
		List<Method> methods = Reflection.methodsWithAnnotation(clazz, Path.class);
		
		for(Method method: methods){
			Path path = method.getAnnotation(Path.class);
			
			PathMacher pathMacher = PathMacher.parse( path.value() );
			actions.add(new Entry(pathMacher, method));
		}
	}
	
	public void loadForFilter(Class<? extends IlPizzeFilter> clazz) {
		List<Method> methods = Reflection.methodsWithAnnotation(clazz, Filter.class);
		
		for(Method method: methods){
			PathMacher pathMacher = PathMacher.parse(PathMacher.FILTER);
			actions.add(new Entry(pathMacher, method));
		}
	}
	
	public Action resolve(HttpServletRequest req) {
		for(Entry entry: actions){
			PathMacher matcher = entry.matcher;
			Map<String, String> pathVariables = matcher.match(req.getPathInfo());
			if(pathVariables != null){
				return new Action(entry.method, pathVariables);
			}
		}
		return null;
	}

	
	private class Entry {
		private PathMacher matcher;  
		private Method method;
		
		private Entry(PathMacher matcher, Method method) {
			this.matcher = matcher;
			this.method = method;
		}
		
		
	}
}
